use crate::MessageRequest;
use bytes::BufMut;
use rseip_core::codec::{Encode, Encoder};

impl<P: Encode, D: Encode> Encode for MessageRequest<P, D> {
    #[inline]
    fn encode<A: Encoder>(self, buf: &mut bytes::BytesMut, encoder: &mut A) -> Result<(), A::Error>
    where
        Self: Sized,
    {
        // service code
        buf.put_u8(self.service_code);

        let path_len = self.path.bytes_count();
        debug_assert!(path_len <= u8::MAX as usize && path_len % 2 == 0);
        buf.put_u8((path_len / 2) as u8);

        self.path.encode(buf, encoder)?;
        self.data.encode(buf, encoder)?;
        Ok(())
    }

    #[inline]
    fn encode_by_ref<A: Encoder>(
        &self,
        buf: &mut bytes::BytesMut,
        encoder: &mut A,
    ) -> Result<(), A::Error> {
        // service code
        buf.put_u8(self.service_code);

        let path_len = self.path.bytes_count();
        debug_assert!(path_len <= u8::MAX as usize && path_len % 2 == 0);
        buf.put_u8((path_len / 2) as u8);

        self.path.encode_by_ref(buf, encoder)?;
        self.data.encode_by_ref(buf, encoder)?;
        Ok(())
    }

    #[inline]
    fn bytes_count(&self) -> usize {
        2 + self.path.bytes_count() + self.data.bytes_count()
    }
}
